package wang.hu.bos.web.action.system;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import wang.hu.bos.domain.system.User;
import wang.hu.bos.service.system.UserService;
import wang.hu.bos.web.action.BaseAction;

import com.opensymphony.xwork2.ActionContext;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
public class UserAction extends BaseAction<User> {
	@Autowired
	private UserService userService;

	private String key;
	private String[] roleIds;

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	public void setKey(String key) {
		this.key = key;
	}

	@Action(value = "user_login", results = {
			@Result(name = "success", location = "./index.html", type = "redirect"),
			@Result(name = "login", location = "./login.html", type = "redirect") })
	public String login() {
		String key2 = (String) ServletActionContext.getRequest().getSession()
				.getAttribute("key");
		if (!key2.equalsIgnoreCase(key)) {
			return LOGIN;
		}
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken token = new UsernamePasswordToken(
				model.getUsername(), model.getPassword());
		try {
			subject.login(token);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return LOGIN;
		}
	}

	@Action(value = "user_list", results = { @Result(name = "success", type = "json") })
	public String list() {
		List<User> list = userService.findAll();
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}

	@Action(value = "user_save", results = { @Result(name = "success", location = "./pages/system/userlist.html", type = "redirect") })
	public String save() {
		userService.save(model, roleIds);
		return SUCCESS;
	}

}
